package com.shw.system.sms.aliyun;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.shw.system.common.exception.SmsException;
import com.shw.system.common.utils.StringUtils;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;


/**
 * <Aliyun发送短信>
 *
 * @author wangxu
 * @version 1.0
 * @date 2020/04/17 13:48
 */
@Slf4j
@Component
public class AliyunSendSms implements InitializingBean {

    /**
     * 短信API请求地址
     */
    private static final String REQUEST_RUL = "dysmsapi.aliyuncs.com";

    /**
     * 短信API访问keyId   注：获取不到配置属性时 指定默认值empty避免程序报错
     */
    @Value("${sms.aliyun.accessKeyId:empty}")
    private String accessKeyId;

    /**
     * 短信API访问key的密钥
     */
    @Value("${sms.aliyun.accessKeySecret:empty}")
    private String accessKeySecret;

    /**
     * 签名 注：短信内容=签名+模板
     */
    @Value("${sms.aliyun.signName:empty}")
    private String signName;


    /**
     * 发送验证码
     *
     * @param templateCode 验证码模板代码
     * @param phone        手机号码
     * @param templateParams   模板参数
     * @throws SmsException 短信异常
     */
    public void sendMsg(String templateCode, String phone, Map<String, String> templateParams) throws SmsException {
        String defaultValue = "empty";
        if (defaultValue.equals(accessKeyId) || defaultValue.equals(accessKeySecret) || defaultValue.equals(signName)) {
            throw new SmsException("获取Aliyun短信配置失败, 请检查是否正确配置以下属性{accessKeyId, accessKeySecret, signName}");
        }
        if (StringUtils.isEmpty(templateCode)) {
            throw new SmsException("短信模板不能为空！");
        }
        if (StringUtils.isEmpty(phone)) {
            throw new SmsException("手机号码不能为空！");
        }
        if (templateParams == null || templateParams.size() == 0) {
            throw new SmsException("模板参数不能为空！");
        }

        //参数 服务器名称
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        //请求方式
        request.setMethod(MethodType.POST);
        //请求地址
        request.setDomain(REQUEST_RUL);
        //对应的版本号
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //电话号码
        request.putQueryParameter("PhoneNumbers", phone);
        //签名
        request.putQueryParameter("SignName", signName);
        //模板code
        request.putQueryParameter("TemplateCode", templateCode);
        //模板参数
        String paramsJson = JSON.toJSONString(templateParams);
        log.info("Request模板参数：{}", paramsJson);
        request.putQueryParameter("TemplateParam", paramsJson);
        try {
            //发送请求
            log.info("开始向手机号{}发送短信...", phone);
            CommonResponse response = client.getCommonResponse(request);
            JSONObject resultMap = JSON.parseObject(response.getData());
            String respCode = resultMap.getString("Code");
            if ("OK".equals(respCode)) {
                log.info("向手机号{}发送短信成功, responseData: {}", phone, response.getData());
            } else {
                throw new SmsException("短信发送失败（"+respCode+"）," + AliyunSmsErrorCode.getAliyunSmsErrorCode().get(respCode) + "!");
            }
        } catch (ServerException e) {
            throw new SmsException("短信发送失败,服务器错误！", e);
        } catch (ClientException e) {
            throw new SmsException("短信发送失败,客户端错误！", e);
        }
    }


    @Override
    public void afterPropertiesSet() {
        String defaultValue = "empty";
        if (!defaultValue.equals(accessKeyId) || !defaultValue.equals(accessKeySecret) || !defaultValue.equals(signName)) {
            log.info("短信Props完成初始化...");
            log.info("----------accessKeyId: {}", accessKeyId);
            log.info("----------accessKeySecret: {}", accessKeySecret);
            log.info("----------signName: {}", signName);
        }

    }


    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public String getSignName() {
        return signName;
    }


}
